import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/core/network/api_client_provider.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/lifeCircle/application/notification/life_blogger_info_notifier.dart';
import 'package:casdon/modules/lifeCircle/application/notification/life_topic_search_notifier.dart';
import 'package:casdon/modules/lifeCircle/application/notification/life_user_topic_list_notifier.dart';
import 'package:casdon/modules/lifeCircle/data/model/life_topic_module.dart';
import 'package:casdon/modules/lifeCircle/data/repository/life_repository_impl.dart';
import 'package:casdon/modules/lifeCircle/providers/life_search_providers.dart';
import 'package:casdon/modules/lifeCircle/services/follow_status_sync_service.dart';
import 'package:casdon/modules/lifeCircle/ui/widgets/topic_item_widget.dart';
import 'package:casdon/modules/me/data/model/user_center_model.dart';
import 'package:casdon/modules/me/data/repository/me_repository_impl.dart';
import 'package:casdon/modules/me/ui/widgets/circle_avatar_button.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:casdon/common/widget/conform_dialog.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 其他用户的生活圈主页
///
@RoutePage()
class LifeUserHomeScreen extends ConsumerStatefulWidget {
  final String userId;
  final String? nickName;
  final String? avatar;

  const LifeUserHomeScreen({
    super.key,
    required this.userId,
    required this.nickName,
    required this.avatar,
  });

  @override
  ConsumerState<LifeUserHomeScreen> createState() => _LifeUserHomeScreenState();
}

class _LifeUserHomeScreenState extends ConsumerState<LifeUserHomeScreen> {
  @override
  void initState() {
    super.initState();
    Future.microtask(
      () => ref
          .read(lifeBloggerInfoNotifierProvider.notifier)
          .fetchData(widget.userId),
    );
  }

  @override
  Widget build(BuildContext context) {
    final userCenterState = ref.watch(lifeBloggerInfoNotifierProvider);
    final userTopicState = ref.watch(
      lifeUserTopicListNotifierProvider(widget.userId),
    );
    final selfTopicNotifier = ref.watch(
      lifeUserTopicListNotifierProvider(widget.userId).notifier,
    );

    return Scaffold(
      backgroundColor: context.colorScheme.surface,
      body: NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          if (notification is ScrollEndNotification &&
              notification.metrics.pixels >=
                  notification.metrics.maxScrollExtent - 50) {
            selfTopicNotifier.loadMore();
          }
          return false;
        },
        child: RefreshIndicator(
          onRefresh: () async {
            selfTopicNotifier.refresh();
          },
          child: CustomScrollView(
            slivers: [
              /// 顶部紫色区域
              SliverPersistentHeader(
                pinned: true,
                delegate: _BrandHeaderDelegate(
                  userCenter: userCenterState,
                  userId: widget.userId,
                  nickName: widget.nickName,
                  avatar: widget.avatar,
                  isFollowed: userCenterState.isFollow ?? false,
                  topicTotalSize: userTopicState.when(
                    data: (data) => data.totalSize,
                    loading: () => 0,
                    error: (e, st) => 0,
                  ),
                  ref: ref,
                  onFollowStatusChanged: () {
                    // 当关注状态改变时，触发 rebuild
                    setState(() {});
                  },
                ),
              ),

              /// 动态列表
              userTopicState.when(
                loading: () => SliverToBoxAdapter(
                  child: Center(child: CircularProgressIndicator()),
                ),
                error: (error, stackTrace) =>
                    SliverToBoxAdapter(child: Center(child: Text(''))),
                data: (state) => SliverList(
                  delegate: SliverChildBuilderDelegate(
                    (context, index) => TopicItemWidget(
                      topic: state.data![index],
                      showFollowBtn: false,
                      onZanTap: (topic) => _handleZanTap(context, topic, ref),
                      // 用户帖子列表不显示关注按钮
                      onFollowTap: null,
                    ),
                    childCount: state.data?.length,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Future<void> _handleZanTap(
  BuildContext context,
  LifeTopicModule topic,
  WidgetRef ref,
) async {
  try {
    final repository = LifeRepositoryImpl(
      apiClient: ref.read(apiClientProvider),
    );

    final isLiked = topic.isLike;
    final currentLikes = topic.likes;

    // 调用点赞接口
    await repository.likeTopic(
      id: topic.id,
      type: 0, // 0-帖子，1-评论
      flag: isLiked ? 0 : 1, // 0-取消点赞，1-点赞
    );

    // // 更新本地状态，避免刷新整个列表
    final newLikesCount = isLiked ? currentLikes - 1 : currentLikes + 1;

    final submittedKeyword = ref.read(lifeSubmittedKeywordProvider);
    if (submittedKeyword.isNotEmpty) {
      ref
          .read(lifeTopicSearchProvider(submittedKeyword).notifier)
          .updateTopicLikeStatus(topic.id, !isLiked, newLikesCount);
    }

    // 更新当前用户主页列表的状态
    ref
        .read(lifeUserTopicListNotifierProvider(topic.userId).notifier)
        .updateTopicLikeStatus(topic.id, !isLiked, newLikesCount);
  } on DioException catch (e) {
  } catch (e) {
    // 处理错误，可以显示 Toast
    debugPrint("点赞操作失败: $e");
  }
}

/// ---------- Header ----------
class _BrandHeaderDelegate extends SliverPersistentHeaderDelegate {
  final double _height = 242.h;
  final UserCenterModel userCenter;
  final String userId;
  final String? nickName;
  final String? avatar;
  final int topicTotalSize;
  final bool isFollowed;
  final WidgetRef ref;
  final VoidCallback? onFollowStatusChanged;

  _BrandHeaderDelegate({
    required this.userCenter,
    required this.userId,
    required this.nickName,
    required this.avatar,
    required this.topicTotalSize,
    required this.isFollowed,
    required this.ref,
    this.onFollowStatusChanged,
  });

  @override
  double get maxExtent => _height;
  @override
  double get minExtent => _height;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.centerLeft, // 左边开始
          end: Alignment.centerRight, // 右边结束
          colors: [
            Color(0xFF9470FF), // 起始颜色
            Color(0xFF6652F9), // 结束颜色
          ],
        ),
      ),
      child: SafeArea(
        bottom: false,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.only(left: 12.w, right: 12.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    height: 48.h,
                    alignment: Alignment.centerLeft,
                    child: Row(
                      children: [
                        IconButton(
                          icon: const Icon(
                            Icons.arrow_back_ios,
                            color: Colors.white,
                          ),
                          onPressed: () => context.router.maybePop(),
                        ),
                        const Spacer(),
                      ],
                    ),
                  ),
                  SizedBox(height: 24.h),
                  Row(
                    children: [
                      SizedBox(width: 12.w),
                      CircleAvatarButton(
                        imageUrl: avatar,
                        defaultImage: AssetImage(Assets.images.icAvatar.path),
                        size: 48.w,
                        onPressed: () => _handleAvatarClick(context),
                      ),
                      SizedBox(width: 12.w),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              nickName?.isEmpty ?? true ? "匿名用户" : nickName!,
                              style: context.textTheme.headlineLarge!.copyWith(
                                color: Colors.white,
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                            SizedBox(height: 10.h),
                            Row(
                              children: [
                                Text(
                                  "${userCenter.fansTotal}",
                                  style: context.textTheme.bodyLarge!.copyWith(
                                    color: Colors.white,
                                  ),
                                ),
                                Text(
                                  " 粉丝",
                                  style: context.textTheme.bodyMedium!.copyWith(
                                    color: Colors.white,
                                  ),
                                ),
                                SizedBox(width: 25.w),
                                Text(
                                  "${userCenter.followTotal}",
                                  style: context.textTheme.bodyLarge!.copyWith(
                                    color: Colors.white,
                                  ),
                                ),
                                Text(
                                  " 关注",
                                  style: context.textTheme.bodyMedium!.copyWith(
                                    color: Colors.white,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),

                      ElevatedButton(
                        onPressed: () => _handleFollowTap(context),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: isFollowed
                              ? const Color(0xFF6758D4)
                              : Colors.white,
                          foregroundColor: isFollowed
                              ? Colors.white
                              : const Color(0xFF836FFF),
                          elevation: 0,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20),
                            side: BorderSide(color: Colors.white, width: 1),
                          ),
                        ),
                        child: Text(
                          isFollowed ? "已关注" : "关注",
                          style: context.textTheme.bodyLarge?.copyWith(
                            color: isFollowed
                                ? Colors.white
                                : const Color(0xFF836FFF),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            const Spacer(),
            Container(
              padding: EdgeInsets.only(left: 16.w),
              width: double.infinity,
              height: 47.h,
              alignment: Alignment.centerLeft,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(12),
                  topRight: Radius.circular(12),
                ),
                border: const Border(
                  bottom: BorderSide(color: Color(0xFFF0F0F0)),
                ),
              ),
              child: Text(
                "全部动态 ($topicTotalSize)",
                style: context.textTheme.bodyMedium!.copyWith(
                  color: context.customColorThemeNonNull.textColor1,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  bool shouldRebuild(covariant _BrandHeaderDelegate oldDelegate) =>
      oldDelegate.userId != userId ||
      oldDelegate.topicTotalSize != topicTotalSize ||
      oldDelegate.isFollowed != isFollowed;

  void _handleAvatarClick(BuildContext context) {}

  /// 处理关注/取消关注
  Future<void> _handleFollowTap(BuildContext context) async {
    try {
      final repository = MeRepositoryImpl(
        apiClient: ref.read(apiClientProvider),
      );
      final newFollowStatus = !isFollowed;
      // 取消关注前弹确认
      if (isFollowed) {
        final confirm = await showCustomConfirmDialog(
          context: context,
          title: '',
          content: '不再关注该作者？',
          confirmText: '不再关注',
          cancelText: '取消',
        );
        if (confirm != true) return;
      }

      await repository.followUser(
        followUuid: userId,
        flag: isFollowed ? "0" : "1", // "1"：关注，"0"：取消关注
      );
      if (isFollowed == false) {
        ToastUtil.show("关注成功");
      } else {
        ToastUtil.show("取消关注成功");
      }
      // 使用统一的同步服务更新所有相关列表的状态
      final syncService = FollowStatusSyncService(ref);
      syncService.syncFollowStatus(userId, newFollowStatus);

      // 触发 rebuild
      onFollowStatusChanged?.call();
    } on DioException catch (e) {
    } catch (e) {
      debugPrint("关注操作失败: $e");
    }
  }
}
